package com.snail.service.serviceImp;


import com.snail.model.pojo.mall.StockDecreaseRequest;
import com.snail.result.Result;
import com.snail.service.BuyOrder;

import com.snail.service.IBizProductService;
import jakarta.annotation.Resource;
import org.redisson.api.RLock;

import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class BuyOrderImp implements BuyOrder {
    @Resource
    RedissonClient redissonClient;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    // 订单防重时间窗口（秒）
    @Autowired
    BizProductServiceImpl bizProductService;
    private static final long ORDER_DUPLICATE_WINDOW = 10;
    @Autowired
    private IBizProductService productService;
    /**
     * 创建订单 - 防止用户重复提交
     *
     * @return 订单ID
     */
    @Override
    public Boolean createOrder(Long userId, List<StockDecreaseRequest>stockDecreaseRequests) {
        // 防重key（30秒窗口）
        String duplicateKey = "order:duplicate:" + userId + ":";

        // 分布式锁key（用户粒度锁）
        String lockKey = "order:lock:" + userId;
        RLock lock = redissonClient.getLock(lockKey);

        try {
            // 尝试加锁（等待时间100ms，锁持有时间3秒）
            if (!lock.tryLock(100, 3000, TimeUnit.MILLISECONDS)) {
                throw new RuntimeException("系统繁忙，请稍后再试");
            }

            // 防重检查
            Boolean canOrder = stringRedisTemplate.opsForValue().setIfAbsent(
                    duplicateKey,
                    "1",
                    ORDER_DUPLICATE_WINDOW,
                    TimeUnit.SECONDS
            );

            if (Boolean.FALSE.equals(canOrder)) {
                throw new RuntimeException("操作过于频繁，请稍后再试");
            }


            for (StockDecreaseRequest request : stockDecreaseRequests) {
                bizProductService.decreaseStock(request.getProductId(), request.getQuantity());
            }




//            Result<?> stockResult = productService.decreaseStocks(stockDecreaseRequests);
//            if (!stockResult.getCode().equals("00000")) {
//                throw new RuntimeException(stockResult.getMsg());
//            }

            // 实际创建订单
            return true;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("系统异常", e);
        } finally {
            //检查当前线程是否持有这个锁
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
